import { ElMessage } from 'element-plus'
import router from '../router'
import axios from "axios";
import {Base64 } from "js-base64";
const request = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 30000  // 后台接口超时时间设置
})

// request 拦截器
// 可以自请求发送前对请求做一些处理
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    let user = localStorage.getItem("student-user") || localStorage.getItem("teacher-user");
    if (user) {
        config.headers['token'] = Base64.encode(JSON.stringify(user));
    }
    return config;
}, error => {
    return Promise.reject(error);
});


// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
    response => {
        let res = response.data;
        if (response.config.responseType === 'blob') {
            return res;
        }
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res;
        }
        if (res.code === '401') {
            ElMessage.error(res.msg);
            let user = localStorage.getItem("student-user") || localStorage.getItem("teacher-user");
            if (user && user.includes("teacher")) {
                router.push("/teacher-login"); // 假设教师登录页面为 '/teacher-login'
            } else {
                router.push("/student-login"); // 假设学生登录页面为 '/student-login'
            }
        }
        return res;
    },
    error => {
        console.log('err' + error);
        return Promise.reject(error);
    }
);



export default request
